import { Button, Input, InputRef,Space, message } from "antd";
import React, { useEffect, useRef, useState } from "react"


enum Status {
  wait,
  success,
  fail,
}

function App(): JSX.Element {

  /* 随机结果 */
  const [result, setResult] = useState<number>();
  /* 猜数字次数 */
  const [count, setCount] = useState<number>(0);
  /* 猜数字判定 */
  const [status, setStatus] = useState<Status>(Status.wait);
  /* 输入数字结果集 */
  const [valList, setValList] = useState<number[]>([]);
  /* 输入数据 */
  const [value, setValue] = useState<string>("");

  /* 提价猜测结果 */
  const guess = () => {
    if(!value) return;
    const val = Number(value);
    if (val === result) {
      setStatus(Status.success);
    } else {
     setStatus(Status.fail); 
    }
    setValList([val,...valList])
    setCount(count + 1);
  }

  /* 再来一次 */
  const restart = () => {
    setResult(Math.floor(Math.random() * 100) + 1);
    setCount(0);
    setValue('');
    setStatus(Status.wait);
    setValList([]);
  }


  useEffect(() => {
    restart();
  },[])

  return (
    <div className='project-container w-[100vw] h-[100vh] px-10 overflow-x-hidden'>
      <header><h3 className="text-center text-[20px] py-4">猜数字</h3></header>
      <main>
        <div>
          <Space size="small"  direction="vertical">
            <p>请输入一个1到100之间的数字</p>
            <Input type="text" value={value} onChange={(e) => {
              setStatus(Status.wait);
              const val = e.target.value;
              if(!/^\d+$/.test(val)){
                setValue("");
                message.error("请输入一个数字");
                return;
              }
              setValue(val);
            }}/>
            <div>
              <Button type="primary" onClick={guess} >这次肯定对</Button>
              <Button className="ml-2" type="primary" onClick={restart}>再来一次</Button>
            </div>
          </Space>
        </div>
        <div className="py-2">
        <Space size="small"  direction="vertical">
          <p>猜了{count}次</p>
          {status === Status.success && <p>{count > 10 ? "恭喜你，猜对了！" : `你太厉害了，只用了${count}次就猜对了！`}</p>}
          {status === Status.fail && <p>不好意思，你{count > 1 ? "又" : ""}猜错了，这次数字{(valList[0] || 0) > (result || 0) ? "大" : "小"}了</p>}
          <ul>
            {valList.map((val, index) => <li key={index}>第{valList.length - index}次输入数字：{val}</li>)}
          </ul>
        </Space>
        </div>
      </main>
    </div>
  )
}

export default App
